import {
    View, FlatList, RefreshControl, TouchableOpacity,
    TouchableHighlight, Text, StyleSheet, Image, Alert, DatePickerAndroid
} from 'react-native';
import React, { PureComponent } from 'react';
import Urls, { getRealUrl } from '../const/Urls'
import LocalImg from '../const/Images'
import moment from 'moment'

/**
 * 值班情况
 */
class PageZbqk extends PureComponent {

    constructor(props) {
        super(props);
        let date = new Date();
        date.setTime(date.getTime() - 24 * 60 * 60 * 1000 * 30);
        this.user = this.props.user;
        this.state = {
            data: [],
            isLoading: false,
            endDate: new Date(),
        }
    }

    componentDidMount() {
        this.setState({
            data: [],
        });
        this.loadData();
    }


    render() {
        return (
            <View style={{ flexDirection: 'column', flex: 1 }}>
                <View style={{
                    flexDirection: 'row',
                    flex: 0,
                    height: 60,
                    alignItems: 'center',
                    justifyContent: 'center',
                    backgroundColor: '#0066FF'
                }}>
                    <View style={{ flex: 1, padding: 10 }}>
                        <TouchableOpacity onPress={() => this.props.navigation.pop()}>
                            <Image source={LocalImg['backImg']} style={{ height: 30, width: 30, resizeMode: 'contain' }} />
                        </TouchableOpacity>
                    </View>
                    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                        <Text style={{ fontSize: 20, color: '#ffffff' }}>值班情况</Text>
                    </View>

                    <View style={{ flex: 1, alignItems: 'flex-end', padding: 10 }}>

                    </View>
                </View>

                <View style={{ flexDirection: 'row', margin: 10, alignItems: 'center' }}>
                    <View>
                        <Text style={{ fontSize: 18 }}>日期</Text>
                    </View>
                    <TouchableOpacity onPress={() => this.selectEndDate()} style={{ flex: 1 }}>
                        <View style={{
                            flex: 1,
                            flexDirection: 'row',
                            borderBottomWidth: 1,
                            borderColor: '#000000'
                        }}>
                            <Text style={{
                                textAlign: 'center',
                                flex: 1,
                                width: 100
                            }}>{this.getFormatDate(this.state.endDate)}</Text>
                        </View>
                    </TouchableOpacity>
                    <View>
                        <TouchableHighlight onPress={() => this.search()}>
                            <Text style={{ fontSize: 18 }}>查询</Text>
                        </TouchableHighlight>
                    </View>
                </View>

                <View style={{
                    flexDirection: 'row',
                    backgroundColor: '#f9f9f9',
                    padding: 10,
                    justifyContent: 'center',
                    alignItems: 'center'
                }}>
                    <View style={{ flex: 1 }}>
                        <Text style={{ fontWeight: 'bold' }}>顺序号</Text>
                    </View>
                    <View style={{ flex: 1 }}>
                        <Text style={{ fontWeight: 'bold' }}>小组号</Text>
                    </View>
                    <View style={{ flex: 1 }}>
                        <Text style={{ fontWeight: 'bold' }}>姓名</Text>
                    </View>
                    <View style={{ flex: 1 }}>
                        <Text style={{ fontWeight: 'bold' }}>值班标志</Text>
                    </View>
                </View>


                <FlatList
                    data={this.state.data}
                    renderItem={(item, index) => this.renderRow(item, index)}
                    keyExtractor={this.keyExtractor}
                    ItemSeparatorComponent={this.separator}
                    ListFooterComponent={() => this.footerView()}
                    onEndReachedThreshold={0.1}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isLoading}
                            onRefresh={() => this.onRefresh()}
                        />
                    } />

            </View>
        )
    }

    keyExtractor = (item, index) => item.YHYID + "";

    footerView() {
        return (
            <View style={{ flexDirection: 'row', justifyContent: 'center', paddingTop: 20, paddingBottom: 30 }}>
                <Text>到底了</Text>
            </View>
        )
    }


    onRefresh() {
        this.setState({
            data: [],
        });
        this.loadData();
    }


    loadData() {

        this.setState({
            isLoading: true
        });

        const request = new Map();
        request.set('date', this.getFormatDate(this.state.endDate));
        fetch(getRealUrl(Urls['zbqkUrl'], request), {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            },
        })
            .then(response => response.json())
            .then(responseJson => {
                if (responseJson instanceof Array) {
                    this.setState({
                        data: this.state.data.concat(responseJson),
                    });
                }
                this.setState({
                    isLoading: false
                })
            })
            .catch(error => {
                console.error(error);
                this.setState({
                    isLoading: false
                });
            });


    }

    separator(index) {
        return (
            <View key={index} style={{ height: 1, backgroundColor: '#CCCCCC' }} />
        )
    }

    processDateTime(date) {
        const m = moment(date)
        if (m.isValid()) {
            return m.format('DD/HHmm')
        } else
            return ""
    }


    renderRow({ item, index }) {

        let bColor = index % 2 !== 0 ? "#f9f9f9" : "#ffffff";
        let show = item.YHYID === '';
        let style = 'flex';
        if (show) {
            style = 'none'
        }
        return (

            <TouchableHighlight key={item.YHYID} style={{ display: style }}>
                <View style={{
                    flexDirection: 'row',
                    padding: 10,
                    backgroundColor: bColor,
                    justifyContent: 'center',
                    alignItems: 'center',
                }}>
                    <View style={{ flex: 1 }}>
                        <Text>{item.NSORT}</Text>
                    </View>
                    <View style={{ flex: 1 }}>
                        <Text>{item.FZBH}</Text>
                    </View>
                    <View style={{ flex: 1 }}>
                        <Text>{item.YHYXM}</Text>
                    </View>
                    <View style={{ flex: 1 }}>
                        <Text>{item.SFZB}</Text>
                    </View>
                </View>
            </TouchableHighlight>

        )
    }
    getFormatDate(date) {
        const m = moment(date);
        if (m.isValid()) {
            return m.format('YYYY-MM-DD')
        } else
            return ""
    }
    search() {
        this.setState({
            data: [],
        });
        this.loadData();
    }
    async selectEndDate() {
        try {
            const { action, year, month, day } = await DatePickerAndroid.open({
                date: this.state.endDate
            });
            if (action !== DatePickerAndroid.dismissedAction) {
                // 这里开始可以处理用户选好的年月日三个参数：year, month (0-11), day
                this.setState({
                    endDate: new Date(year, month, day),
                })
            }
        } catch ({ code, message }) {
            console.warn('Cannot open date picker', message);
        }
    }
}

const styles = StyleSheet.create({
    phone: {
        flex: 1,
        textDecorationLine: 'underline',
        color: '#0066FF',
    },
    text: {
        flex: 1
    },
    row: {
        flexDirection: 'column',
        justifyContent: 'center',
        padding: 10,
    },
});


export default PageZbqk;